<template>
  <el-button type="primary" @click="handleLike">
    {{ articleDetail.isLiked ? '取消点赞' : '点赞' }}
  </el-button>
</template>

<script>
import { getArticleDetail, likeArticle, unlikeArticle, checkArticleLiked } from '@/api/community'

export default {
  data() {
    return {
      articleDetail: {},
      articleId: null
    }
  },
  methods: {
    async handleLike() {
      try {
        if (this.articleDetail.isLiked) {
          await unlikeArticle(this.articleId)
          this.articleDetail.likeCount--
        } else {
          await likeArticle(this.articleId)
          this.articleDetail.likeCount++
        }
        // 重新检查点赞状态
        const likedRes = await checkArticleLiked(this.articleId)
        if (likedRes.code === 0) {
          this.articleDetail.isLiked = likedRes.data
        }
      } catch (error) {
        console.error('点赞操作失败:', error)
      }
    },
    async fetchArticleDetail() {
      try {
        const res = await getArticleDetail(this.articleId)
        if (res.code === 0) {
          this.articleDetail = res.data
          // 检查是否已点赞
          const likedRes = await checkArticleLiked(this.articleId)
          if (likedRes.code === 0) {
            this.articleDetail.isLiked = likedRes.data
          }
        }
      } catch (error) {
        console.error('获取文章详情失败:', error)
      }
    }
  },
  mounted() {
    // 你需要根据实际情况设置 articleId
    // this.articleId = ...
    this.fetchArticleDetail()
  }
}
</script>